//
//  ZGSMoreCartoonViewController.m
//  MapleLeaf
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "ZGSMoreCartoonViewController.h"
#import "ZGSHomeHeaderModel.h"
#import "ZGSHomeCartoonModel.h"
#import "ZGSCartoonCell.h"
#import "ZGSCartoonDetailsViewController.h"



@interface ZGSMoreCartoonViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *listArr;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, assign) NSInteger next;

@end

@implementation ZGSMoreCartoonViewController

- (void)viewWillAppear:(BOOL)animated {
    //设置标题
    if (self.header) {
        self.title = self.header.name;
        
    }else {
        self.title = self.keyWord;
    }
    
    //设置导航栏
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1.000f green:0.267f blue:0.000f alpha:1.00f];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor whiteColor], NSForegroundColorAttributeName , nil]];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.count = 1;
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self createData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)createData {
    if ([self.tableView.mj_footer isRefreshing]) {
    
        //判断请求
        if (self.next == 1) {
            if (self.header.tId) {
                NSString *strURL = [NSString string];
                strURL = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/column/more?columnId=%@&type=2&market=20&page=%ld&size=20", self.header.tId, self.page];

                [BaseAFN GETURLByString:strURL AFNData:^(id result) {
                    self.next = [result[@"data"][@"next"] integerValue];
                    NSMutableArray *arr = result[@"data"][@"list"];
                    NSMutableArray *tempArr = [ZGSHomeCartoonModel baseModelByArr:arr];
                    [self.listArr addObjectsFromArray:tempArr];
                    
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView reloadData];
                    
                }];
            }else if ([self.keyWord isEqualToString:@"热门"]) {
                NSString *strURL = [NSString string];
                
                strURL = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/list/hot?market=20&page=%ld&size=20&appversion=21", self.page];
                
                [BaseAFN GETURLByString:strURL AFNData:^(id result) {
                    self.next = [result[@"data"][@"next"] integerValue];
                    NSMutableArray *arr = result[@"data"][@"list"];
                    NSMutableArray *tempArr = [ZGSHomeCartoonModel baseModelByArr:arr];
                    [self.listArr addObjectsFromArray:tempArr];
                    
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView reloadData];
                    
                    
                }];
                
                
            }else if ([self.keyWord isEqualToString:@"最新"]) {
                NSString *strURL = [NSString string];
                strURL = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/list/last?market=20&page=%ld&size=20&appversion=21", self.page];
                [BaseAFN GETURLByString:strURL AFNData:^(id result) {
                    self.next = [result[@"data"][@"next"] integerValue];
                    NSMutableArray *arr = result[@"data"][@"list"];
                    NSMutableArray *tempArr = [ZGSHomeCartoonModel baseModelByArr:arr];
                    [self.listArr addObjectsFromArray:tempArr];
                    
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView reloadData];
                    
                    
                }];
            }
            
        }
    
    
    }else {
//        BaseAFN GETURLByString:<#(NSString *)#> AFNData:<#^(id result)block#>
        NSString *strURL = [NSString string];
        if (self.header.tId) {
            
            self.page = 1;
            self.count++;
            
            strURL = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/column/more?columnId=%@&type=2&market=20&page=1&size=20", self.header.tId];
            NSLog(@"%@", strURL);
        }
        else {
            if ([self.keyWord isEqualToString:@"热门"]) {
                strURL = @"http://api.youqudao.com/mhapi/api/list/hot?market=20&page=1&size=20&appversion=21";
            }
            else if ([self.keyWord isEqualToString:@"最新"]) {
                strURL = @"http://api.youqudao.com/mhapi/api/list/last?market=20&page=1&size=20&appversion=21";
            }
            else {
                NSString *str = [NSString stringWithFormat:@"http://api.youqudao.com/mhapi/api/list/search?market=20&customerId=1913463&uuid=64:b4:73:28:fd:2c&keyWord=%@&startIndex=0&size=20&categoryId=-1&appversion=21", self.keyWord];
                strURL = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            };
        }

        [BaseAFN GETURLByString:strURL AFNData:^(id result) {
            self.next = [result[@"data"][@"next"] integerValue];
            NSMutableArray *arr = result[@"data"][@"list"];
            self.listArr = [NSMutableArray array];
            self.listArr = [ZGSHomeCartoonModel baseModelByArr:arr];
            
            [self.tableView reloadData];
            if (self.count == 1) {
                [self.hud removeFromSuperview];
            }
            [self.tableView.mj_header endRefreshing];
 
            
        }];
    }
}



#pragma mark - tableDateSource & Delegate

- (UITableView *)tableView {
    
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
        _tableView.separatorStyle = NO;
        _tableView.rowHeight = HEIGHT / 5.0;
        [self.view addSubview:_tableView];
        
        [self.tableView registerClass:[ZGSCartoonCell class] forCellReuseIdentifier:@"listReuse"];
        
        // 上拉下拉
        MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(createData)];
        self.tableView.mj_header = header;
        MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(createData)];
        self.tableView.mj_footer = footer;
        
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
    }
    return _tableView;
}



#pragma mark tableViewDelegate & DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZGSCartoonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listReuse" forIndexPath:indexPath];
    
    ZGSHomeCartoonModel *cartoon =self.listArr[indexPath.row];
    
    // 转码
    NSString * encodingString = [cartoon.coverPic stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [cell.picView sd_setImageWithURL:[NSURL URLWithString:encodingString] placeholderImage:[UIImage imageNamed:@"backgroundImage.png"]];
    
    cell.titleLabel.text = cartoon.name;
    cell.authorLabel.text = cartoon.author;
    
    // 话数高亮
    NSInteger length = [cartoon.updateSize stringValue].length;
    NSString *totalString = [NSString stringWithFormat:@"更新至%@话(连载中)", cartoon.updateSize];
    NSMutableAttributedString *tMutaString = [[NSMutableAttributedString alloc] initWithString:totalString];
    [tMutaString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3,length)];
    cell.totalLabel.attributedText = tMutaString;
    
    // 热度
    //    NSString *
    NSString *popularString = [NSString stringWithFormat:@"☆%@", cartoon.popular];
    NSMutableAttributedString *pMutaString = [[NSMutableAttributedString alloc] initWithString:popularString];
    [pMutaString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,1)];
    cell.popularLabel.textAlignment = NSTextAlignmentRight;
    cell.popularLabel.attributedText = pMutaString; //∆
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZGSCartoonDetailsViewController * cdVC = [[ZGSCartoonDetailsViewController alloc] init];
    ZGSHomeCartoonModel *cartoon = self.listArr[indexPath.row];
    cdVC.albumId = cartoon.albumId;
    [self.navigationController pushViewController:cdVC animated:YES];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
